import axios, { type AxiosInstance } from 'axios'
import { userInfo } from '@/store/userInfo.ts'
import { envBase } from '@/config/apiConfig/env.ts'

// 配置新建一个 axios 实例
const service: AxiosInstance = axios.create({
  baseURL: envBase,
  timeout: 60000,
  headers: { 'Content-Type': 'application/json' },
})

service.interceptors.request.use(
  (config) => {
    const userInfoStore = userInfo()
    if (userInfoStore.token) {
      config.headers.Authorization = 'Bearer ' + userInfoStore.token
    }
    return config
  },
  async (error) => {
    return await Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    return response
  },
  async (error) => {
    return await Promise.reject(error)
  }
)

export default service
